<!-- SpontaneousMomentsSubmit_Win.html -->
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
		<meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
		<title>上传精彩瞬间图片</title>
		<link rel="stylesheet" href="../../css/mui.min.css" />
		<link rel="stylesheet" type="text/css" href="../../css/weui.min.css">
		<link rel="stylesheet" href="../../css/base.css">
		<style type="text/css">
			.base-nav-item{
				text-decoration:none;
			}
			.base-nav-item:active{
				color: #e0e0e0;
			}
			.base_left_item{
				text-align: right;
			}
			.pic-f-div{
				position: relative;
				padding: 10px;
			}
			.pic-cell-div{
				width: 33.3%;
				padding-bottom: 33.3%;
				float: left;
				position: relative;
			}
			.pic-s-div{
				position: absolute;
				left: 4px;
				top: 4px;
				width: calc(100% - 8px);
				height: calc(100% - 8px);
				background-image: url(../../image/course_placehoder.png);
				background-repeat: no-repeat;
			    background-size: cover;
			    background-position: center;
			}
			.add-more{
				background-image: url(../../image/add_pic.png);
			}
			.pic-s-delete{
				width: 20px;
				height: 20px;
				position: absolute;
				right: 0;
				top: 0;
				background-image: url(../../image/remove.png);
				background-size: cover;
				background-repeat: no-repeat;
			}
		</style>
	</head>
	<body>
		<div class="base_style_color " id='BarAppearance' style="height: 22px;width: 100%"></div>
		<div class="base_navigation_bar base_style_color base_navigation_item_bar">
			<a class="base-nav-item base_left_item" href="#" onclick="backClick()">取消</a>
			<span>上传照片</span>
			<a class="base-nav-item base_right_item" href="#" onclick="submitClick()">上传</a>
		</div>
		<div class="base_content_div">
			<div class="pic-f-div">
				<div id="select_photo_list">
					<!-- <div class="pic-cell-div">
						<div class="pic-s-div"></div>
						<div class="pic-s-delete"></div>
					</div> -->
				</div>
				<div id="add_more_btn" class="pic-cell-div">
					<div class="pic-s-div add-more" onclick="onSelectPhotoClick()"></div>
				</div>
			</div>
		</div>
		<div id="picture" class="mui-popover mui-popover-action mui-popover-bottom">
			<ul class="mui-table-view">
				<li class="mui-table-view-cell">
					<a href="#" typeid="0" style="color:#222;">拍照</a>
				</li>
				<li class="mui-table-view-cell">
					<a href="#" typeid="1" style="color:#222;">从相册选取</a>
				</li>
			</ul>
			<ul class="mui-table-view">
				<li class="mui-table-view-cell">
					<a href="#picture" typeid="2" style="color:#222;"><b>取消</b></a>
				</li>
			</ul>
		</div>
		<div id="offlineAlert" class="weui_dialog_confirm" hidden="hidden">
			<div class="weui_mask"></div>
			<div class="weui_dialog">
				<div class="weui_dialog_hd">
					<strong class="weui_dialog_title">是否放弃在此页面操作？</strong>
				</div>
				<div class="weui_dialog_bd"></div>
				<div class="weui_dialog_ft">
					<a onclick="onCancelClick()" href="#" class="weui_btn_dialog default"  style="color:#18b4ed">取消</a>
					<a onclick="onConfirmClick()" href="#" class="weui_btn_dialog primary"  style="color:#18b4ed">确定</a>
				</div>
			</div>
		</div>
	</body>
	<script type="text/javascript" src="../../script/api.js"></script>
	<script type="text/javascript" src="../../script/jquery.min.js"></script>
	<script type="text/javascript" src="../../script/mui.min.js"></script>
	<script type="text/javascript" src="../../script/MD5.js"></script>
	<script type="text/javascript" src="../../script/requestTool.js"></script>
	<script type="text/javascript" src="../../script/processing_images.js"></script>
	<script type="text/javascript" src="../../script/timeStampTool.js"></script>
	<script type="text/javascript">
		var currentPhotos = new Array();
		var selectedPhotos = new Array();
		apiready = function() {
			
		}
		function submitClick(){
			if (selectedPhotos.length > 0) {
				api.showProgress({
				    style: 'default',
				    animationType: 'fade',
				    title: '',
				    text: '上传图片中...',
				    modal: false
				});
				uploadPhotos(function(){
					submitPhotos();
				});
			}else{
				api.toast({
				    msg: '请选择图片后再提交'
				});
			}
		}
		function uploadPhotos(callback){
			var index = 0;
			for (var i = 0; i < selectedPhotos.length; i++) {
				var picData = selectedPhotos[i];
				uploadSinglePhoto(picData, function(ret){
					// console.log(JSON.stringify(picData)+'\n'+JSON.stringify(ret));
					if (ret) {
						currentPhotos.push(ret);
					}
					index++;
					if (index == selectedPhotos.length) {
						callback();
					}
				});
			}
		}
		function submitPhotos(){
			var params = {
				uid : $api.getStorage('cfnetppuid'),
				jid : $api.getStorage('cfnetppjxid'),
				planid : api.pageParam.pid,
				courseid : api.pageParam.cid,
				imgArr : currentPhotos
			};
			cfnetppPOST(url_submitSpontaneousMomentsPics, params, false, function(data, status){
				api.hideProgress();
				if (status == 'success') {
					if (data.code == 200) {
						api.toast({
						    msg: '上传图片成功'
						});
						api.sendEvent({
						    name: 'refreshPicListNotifi'
						});
						setTimeout(function(){
							api.closeWin();
						}, 1000);
					}else{
						api.toast({
						    msg: '上传图片失败，请重试'
						});
					}
				}else{
					api.toast({
					    msg: '上传图片失败，请重试'
					});
				}
			});
		}
		function fileNameWithPath(path){
			var urlArr = path.split("/");        //截取路径
 			var getName = urlArr[urlArr.length - 1]; //获取文件的名字 
 			return getName;
		}
		function onSelectPhotoClick(){
			mui('#picture').popover('toggle');
			mui('body').on('tap', '.mui-popover-action li>a', function() {
				mui('#picture').popover('hide');
				var typeid = $(this).attr('typeid');
				if (typeid == 0) {//相机
					openCamera(function(ret){
						addCameraPic(ret.data, function(){
							setupCurrentSelectedPics();
						});
					});
				}else if(typeid = 1){//相册
					selectPhotos(function(ret){
						addAlbumPicWithArr(ret.list, function(){
							setupCurrentSelectedPics();
						});
					});
				}
			});
		}
		//设置选中图片显示
		function setupCurrentSelectedPics(){
			var picCount = selectedPhotos.length;
			if (picCount >= 9) {
				$('#add_more_btn').hide();
			}else{
				$('#add_more_btn').show();
			}
			var htmlString = '';
			for (var i = 0; i < picCount; i++) {
				var picData = selectedPhotos[i];
				htmlString += photoHtmlWidthData(picData, i);
			}
			$('#select_photo_list').html(htmlString);
			$('.pic-s-delete').unbind('click');
			$('.pic-s-delete').click(function(){
				var index = parseInt($(this).attr('index'));
				selectedPhotos.splice(index, 1);
				setupCurrentSelectedPics();
			});
		}
		function photoHtmlWidthData(picData, index){
			return '<div index="'+index+'" class="pic-cell-div">'+
						'<div class="pic-s-div" style="background-image: url('+picData.picurl+');"></div>'+
						'<div class="pic-s-delete" index="'+index+'"></div>'+
					'</div>';
		}
		function addCameraPic(picPath, callback){
			if (picPath == null || picPath == undefined || picPath == '') {
				return;
			}
			var nowTime = getNowDate() / 1000;
			var picData = {
				picurl : picPath,
				shootingTime : nowTime,
				picname : fileNameWithPath(picPath)
			};
			selectedPhotos.push(picData);
			callback();
		}
		function addAlbumPicWithArr(picArr, callback){
			if (picArr == null || picArr == undefined || picArr == '') {
				return;
			}
			var index = 0;
			for (var i = 0; i < picArr.length; i++) {
				var picData = picArr[i];
				selectedPhotos.push({
					picurl : picData.path,
					shootingTime : timeStampWithTimeString(picData.time),
					picname : fileNameWithPath(picData.path)
				});
			}	
			callback();
		}
		function uploadSinglePhoto(picData, callback){
			uploadFileToAli(picData.picurl, function(ret) {
				if (ret) {
					callback({
						picurl : ret.fileurl,
						shootingTime : picData.shootingTime,
						picname : picData.picname
					});
				}else{
					callback(null);
				}
			});
		}
		function addAlbumPic(picData, callback){
			uploadFileToAli(picData.path, function(ret) {
				if (ret) {
					callback({
						picurl : ret.fileurl,
						shootingTime : timeStampWithTimeString(picData.time),
						picname : fileNameWithPath(ret.fileurl)
					});
				}else{
					callback(null);
				}
			});
			// addAlbumPic(picData, function(ret){
			// 	if (ret) {
			// 		currentPhotos.push(ret);
			// 	}
			// 	index++;
			// 	if (index == picArr.length) {
			// 		callback();
			// 	}
			// });
		}
		//上传文件至阿里云
		function uploadFileToAli(filePath, callback){
			api.ajax({
				url : Upload_File_img,
				method : 'post',
				timeout : 30,
				dataType : 'json',
				returnAll : false,
				data : {
					values : {
						uid : $api.getStorage('cfnetppuid')
					},
					files : {
						file : filePath
					}
				}
			}, function(ret, err) {
				if (ret) {
					if (ret.status == 1) {
						callback(ret);
					} else {
						callback(null);
					}
				} else {
					callback(null);
				}
			});
		}
		function backClick() {
			if (selectedPhotos.length > 0) {
				$('#offlineAlert').show();
			}else{
				api.closeWin();
			}
		}
		function onCancelClick(){
			$('#offlineAlert').hide();
		}
		function onConfirmClick(){
			api.closeWin();
		}
		//打开相机
		function openCamera(callback){
			api.getPicture({
			    sourceType: 'camera',
			    encodingType: 'jpg',
			    mediaValue: 'pic',
			    destinationType: 'url',
			    quality: 50
			}, function(ret, err) {
			    if (ret) {
			        callback(ret);
			    }
			});
		}
		//打开相册
		function selectPhotos(callback){
			var maxNum = 9 - selectedPhotos.length;
			if (maxNum <= 0) {
				return;
			}
			var UIMediaScanner = api.require('UIMediaScanner');
			UIMediaScanner.open({
			    type: 'picture',
			    column: 4,
			    classify: true,
			    max: maxNum,
			    sort: {
			        key: 'time',
			        order: 'desc'
			    },
			    texts: {
			        stateText: '已选择*项',
			        cancelText: '取消',
			        finishText: '完成'
			    },
			    styles: {
			        bg: '#fff',
			        mark: {
			            icon: '',
			            position: 'bottom_left',
			            size: 20
			        },
			        nav: {
			            bg: '#eee',
			            stateColor: '#000',
			            stateSize: 18,
			            cancelBg: 'rgba(0,0,0,0)',
			            cancelColor: '#000',
			            cancelSize: 18,
			            finishBg: 'rgba(0,0,0,0)',
			            finishColor: '#000',
			            finishSize: 18
			        }
			    },
			    scrollToBottom: {
			        intervalTime: 3,
			        anim: true
			    },
			    exchange: true,
			    rotation: true
			}, function(ret) {
				callback(ret);
			});
		}
	</script>
</html>